package com.ladlee.controller;

import com.ladlee.properties.SecurityConstants;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;

/**
 * @Auther: dingchang
 * @Date: 2018/12/21 12:52
 * @Description:
 */
@Controller
public class LoginController {

    /**
     * 跳转到登录界面
     *
     * @param map
     * @return
     */
    @GetMapping(SecurityConstants.DEFAULT_UNAUTHENTICATION_URL)
    public ModelAndView require(Map<String, Object> map) {
        return new ModelAndView("login", map);
    }

    /**
     * 手机号登录界面
     * @param map
     * @return
     */
    @GetMapping(SecurityConstants.DEFAULT_SIGN_IN_URL_MOBILE_PAGE)
    public ModelAndView mobilePage(Map<String, Object> map) {
        return new ModelAndView("mobileLoginPage", map);
    }

    /**
     * 主页
     *
     * @param userDetails
     * @param map
     * @return
     */
    @GetMapping(value = {"/index", "/"})
    public ModelAndView index(@AuthenticationPrincipal UserDetails userDetails, Map<String, String> map) {
        map.put("username", userDetails.getUsername());
        return new ModelAndView("index", map);
    }

    /**
     * 跳转到主页
     * @param userDetails
     * @param map
     * @return
     */
    @GetMapping(value = "/main")
    public ModelAndView main(@AuthenticationPrincipal UserDetails userDetails, Map<String, String> map) {
        map.put("username", userDetails.getUsername());
        return new ModelAndView("main", map);
    }

    /**
     * 欢迎页
     * @param userDetails
     * @param map
     * @return
     */
    @GetMapping(value = "/hello")
    public ModelAndView hello(@AuthenticationPrincipal UserDetails userDetails, Map<String, String> map) {
        map.put("username", userDetails.getUsername());
        return new ModelAndView("hello", map);
    }

    @GetMapping("/user")
    @ResponseBody
    public Object user(){
        Object object = SecurityContextHolder.getContext().getAuthentication().getPrincipal();//获取spring security封装的当前用户信息对象
        return object;
    }
}
